﻿using Hangfire;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;

namespace Framework.Hangfire.Job_MonitorServer
{
    public class JobService : IJobService
    {
        private readonly IServiceProvider _service; 

        public JobService(IServiceProvider service)
        {
            _service = service; 
        }

        public void EnqueueTasks()
        {
            var jobs = _service.GetServices<IJob>();
            foreach (var job in jobs)
            {
                var attr = job.GetType().IsAssignableTo(typeof(Job_MonitorServerAbstract));
                if (!attr) continue;
                var task = job as Job_MonitorServerAbstract;
                if (!string.IsNullOrEmpty(task!.JobId))
                {
                    if (task.Enable)
                        RecurringJob.AddOrUpdate(task.JobId, () => job.Execute(), task.CronExpression, TimeZoneInfo.Local, task.Queue);
                    else
                        RecurringJob.RemoveIfExists(task.JobId);
                }
            }
        } 
    }
}